<!-- 基础资料----人员台账 -->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="用户姓名" prop="personName">
        <el-input
          v-model="queryParams.personName"
          placeholder="请输入用户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="personPhone">
        <el-input
          v-model="queryParams.personPhone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="所属班组" prop="teamId">
        <el-select
          v-model="queryParams.teamId"
          placeholder="请选择班组"
          clearable
        >
          <el-option
            v-for="item in teams"
            :key="item.id"
            :label="item.teamName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="所属岗位" prop="postId">
        <el-select
          v-model="queryParams.postId"
          placeholder="请选择岗位"
          clearable
        >
          <el-option
            v-for="item in posts"
            :key="item.id"
            :label="item.postName"
            :value="item.id"
          >
          </el-option>
          <!-- <el-option v-for="dict in dict.type.person_post" :key="dict.value" :label="dict.label" :value="dict.value" /> -->
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:person:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:person:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:person:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          >导入</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:person:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="personList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="序号"
        type="index"
        width="100"
        align="center"
        v-if="getColumn('index')"
      >
        <template slot-scope="scope">
          <span>{{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="用户id" align="center" prop="id" v-if="getColumn('id')" /> -->
      <el-table-column
        label="用户姓名"
        align="center"
        prop="personName"
        v-if="getColumn('personName')"
      />
      <el-table-column
        label="用户性别"
        align="center"
        prop="personSex"
        v-if="getColumn('personSex')"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_user_sex"
            :value="scope.row.personSex"
          />
        </template>
      </el-table-column>
     
      <!-- <el-table-column
        label="年龄"
        align="center"
        prop="age"
        v-if="getColumn('age')"
      /> -->

      <el-table-column
        label="联系电话"
        align="center"
        prop="personPhone"
        v-if="getColumn('personPhone')"
      />
      <el-table-column
        label="上岗证编号"
        align="center"
        prop="certificateId"
        v-if="getColumn('certificateId')"
      />
      <el-table-column
        label="所属班组"
        align="center"
        prop="teamId"
        v-if="getColumn('teamId')"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.bus_person_group"
            :value="scope.row.teamId"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="岗位"
        align="center"
        prop="postId"
        v-if="getColumn('postId')"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.bus_person_post"
            :value="scope.row.postId"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="四至"
        align="center"
        prop="border"
        v-if="getColumn('border')"
      /> -->
      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        v-if="getColumn('remark')"
      />
      <el-table-column
        label="头像"
        align="center"
        prop="inspectionPlan"
        width="100"
        v-if="getColumn('inspectionPlan')"
      >
        <template slot-scope="scope">
          <image-preview
            :src="scope.row.inspectionPlan"
            :width="50"
            :height="50"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        v-if="getColumn('operate')"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:person:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:person:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :pageSizes="pageSizes"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改人员台账对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户姓名" prop="personName">
          <el-input v-model="form.personName" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item label="用户性别" prop="personSex">
          <el-select v-model="form.personSex" placeholder="请选择用户性别">
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="personNumber">
          <el-input v-model="form.personNumber" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="联系电话" prop="personPhone">
          <el-input v-model="form.personPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="用户住址" prop="personAddress">
          <el-input v-model="form.personAddress" placeholder="请输入用户住址" />
        </el-form-item>
        <el-form-item label="用户学历" prop="personEducation">
          <el-input
            v-model="form.personEducation"
            placeholder="请输入用户学历"
          />
        </el-form-item>
        <el-form-item label="合同类型" prop="contractType">
          <el-select v-model="form.contractType" placeholder="请选择合同类型">
            <el-option
              v-for="dict in dict.type.contract_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入场时间" prop="einlassTime">
          <el-date-picker
            clearable
            v-model="form.einlassTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择入场时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上岗证编号" prop="certificateId">
          <el-input
            v-model="form.certificateId"
            placeholder="请输入上岗证编号"
          />
        </el-form-item>
        <el-form-item label="班组" prop="teamId">
          <el-select
            v-model="form.teamId"
            placeholder="请选择班组"
          >
            <el-option
              v-for="item in teams"
              :key="item.id"
              :label="item.teamName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="岗位" prop="postId">
          <el-select v-model="form.postId" placeholder="请选择岗位">
            <el-option
              v-for="item in posts"
              :key="item.id"
              :label="item.postName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="取证时间" prop="evidenceTime">
          <el-date-picker
            clearable
            v-model="form.evidenceTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择取证时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上岗证照片" prop="workPhoto">
          <image-upload v-model="form.workPhoto" />
        </el-form-item>
        <!-- <el-form-item label="四至" prop="border">
          <el-input
            v-model="form.border"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="头像" prop="inspectionPlan">
          <image-upload v-model="form.inspectionPlan" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox
            v-model="upload.updateSupport"
          />是否更新已经存在的用户数据
          <el-link type="info" style="font-size: 12px" @click="importTemplate"
            >下载模板</el-link
          >
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPerson,
  getPerson,
  delPerson,
  addPerson,
  updatePerson,
  Teamlist,
} from "@/api/business/person";
import { listPost } from "@/api/business/post";
// 导入模板接口importTemplate
import { importTemplate } from "@/api/system/user";
import { getToken } from "@/utils/auth";
export default {
  name: "Person",
  dicts: ["bus_person_post", "sys_user_sex", "bus_person_group", "contract_type"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 人员台账表格数据
      personList: [],
      //年龄
      age: 1,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //动态下拉 班组list
      teams: [],
      // 岗位list
      posts: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/person/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        personName: null,
        personPhone: null,
        teamId: null,
        postId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        personName: [
          { required: true, message: "用户姓名不能为空", trigger: "blur" },
        ],
        personSex: [
          { required: true, message: "用户性别不能为空", trigger: "change" },
        ],
        personNumber: [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
        ],
        personPhone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
        ],
        teamId: [
          { required: true, message: "班组ID不能为空", trigger: "change" },
        ],
        postId: [
          { required: true, message: "岗位ID不能为空", trigger: "change" },
        ],
      },
      // 列信息
      columns: [
        { key: "index", label: `序号`, visible: true },
        { key: "id", label: "uid", visible: true },
        { key: "personName", label: "用户姓名", visible: true },
        { key: "personSex", label: "用户性别", visible: true },
        { key: "age", label: "年龄", visible: true },
        { key: "personPhone", label: "联系电话", visible: true },
        { key: "certificateId", label: "上岗证编号", visible: true },
        { key: "teamId", label: "班组ID", visible: true },
        { key: "postId", label: "岗位ID", visible: true },
        { key: "border", label: "四至", visible: true },
        { key: "remark", label: "备注", visible: true },
        { key: "inspectionPlan", label: "头像", visible: true },
        { key: "operate", label: `操作`, visible: true },
      ],
      // 分页参数
      pageSizes: [10, 50, 100, 500, 1000],
    };
  },

  created() {
    this.getList();
    this.getTeams();
    this.getPosts();
    // Teamlist().then(response => {
    //   console.log('班组：', response.rows);
    //   this.teams = response.rows.map(item => ({ tid: item.id, teamName: item.teamName }));
    // })
  },
  methods: {
    // 获取下拉框数据
    async getTeams() {
      await Teamlist().then((response) => {
        // console.log("data:", response.rows);
        this.teams = response.rows;
      });
      // console.log("班组下拉框：", this.teams);
    },

    // 获取岗位下拉框数据
    async getPosts() {
      await listPost().then((response) => {
        // console.log("岗位：", response.rows);
        this.posts = response.rows;
      });
      // console.log("岗位下拉框：", this.posts);
    },
    /** 查询人员台账列表 */
    getList() {
      this.loading = true;
      listPerson(this.queryParams).then((response) => {
        this.personList = response.rows;
        // console.log(response.rows);
        // console.log("获取数据");
        console.log(this.personList);

        // 添加年龄项和数据
        this.personList = this.personList.map((item) => {
          return {
            ...item,
            age: item.age ? this.calculateAge(item.personNumber) : 'null',
          };
        });
        
        this.total = response.total;
        this.loading = false;
      });
    },

    // 计算年龄
    calculateAge(personNumber) {
      // if (personNumber.length !== 18) {
      //   this.$modal.msgError("请输入正确的18位身份证号码");
      //   return;
      // }
      const birthYear = personNumber.substring(6, 10);
      const birthMonth = personNumber.substring(10, 12);
      const birthDay = personNumber.substring(12, 14);
      const today = new Date();
      let age = today.getFullYear() - Number(birthYear);
      if (
        today.getMonth() + 1 < Number(birthMonth) ||
        (today.getMonth() + 1 === Number(birthMonth) &&
          today.getDate() < Number(birthDay))
      ) {
        age--;
      }
      this.age = age;

      return age;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        delFlag: null,
        createUser: null,
        createBy: null,
        createTime: null,
        updateUser: null,
        updateBy: null,
        updateTime: null,
        personName: null,
        personSex: null,
        personNumber: null,
        personPhone: null,
        personAddress: null,
        personEducation: null,
        contractType: null,
        einlassTime: null,
        certificateId: null,
        teamId: null,
        postId: null,
        evidenceTime: null,
        workPhoto: null,
        border: null,
        remark: null,
        inspectionPlan: null,
        personPwd: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // console.log(this.personList);
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      console.log("ids:");
      console.log(this.ids);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加人员台账";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getPerson(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改人员台账";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        console.log("提交数据：", this.form);
        if (valid) {
          if (this.form.id != null) {
            updatePerson(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // this.form.delFlag = 0;
            addPerson(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除选中的数据项？")
        .then(function () {
          return delPerson(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // console.log("传入参数：");
      // console.log(this.queryParams);

      // 传递的参数
      this.download(
        "business/person/export",
        {
          ...this.queryParams,
          id: this.ids[0],
        },
        `person_${new Date().getTime()}.xlsx`
      );
    },
    /** 列是否显示 */
    getColumn(key) {
      const res = this.columns.filter((item) => item.key === key);
      if (res.length >= 1) {
        return res[0].visible;
      } else {
        return false;
      }
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
